<!-- eslint-disable vue/no-unused-vars -->
<template>
  <div class="app-container-box">
    <div class="box-tag" />
    <span class="user-manager-title">用户管理</span>
    <div class="warp-line-top" />

    <div class="btn-box">
      <el-button
        type="primary"
        :disabled="edituserDisabled"
        @click="editUserHandler"
      >编辑</el-button>
      <el-button
        type="primary"
        icon="el-icon-refresh"
        @click="refreshUsers"
      />

      <el-pagination
        class="page-box"
        background
        layout="total, prev, pager, next, jumper"
        :total="userListCount"
        :pager-count="pagerCount"
        :page-size="userListQuery.length"
        @current-change="pageChanged"
      />
    </div>

    <div class="table-list-box">
      <el-table
        ref="multipleTable"
        :data="userListData"
        style="width: 100%"
        height="654"
        :header-cell-style="elTableHeaderStyle"
        :cell-style="elTableCellStyle"
        tooltip-effect="dark"
        @current-change="clickRowChange"
      >
        <el-table-column label="选择" min-width="20" style="over" align="center">
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row">
              <i />
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column
          prop="UserName"
          label="用户名"
          align="center"
          min-width="30"
          show-overflow-tooltip
          :formatter="userNameHandler"
        />
        <el-table-column
          prop="NickName"
          label="昵称"
          align="center"
          min-width="40"
          show-overflow-tooltip
        />
        <el-table-column
          prop="UserRoles"
          label="角色"
          align="center"
          min-width="30"
          show-overflow-tooltip
          :formatter="roleNameHandler"
        />
        <el-table-column
          prop="phone"
          label="联系电话"
          align="center"
          min-width="30"
          :formatter="phoneHandler"
        />
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          min-width="40"
          show-overflow-tooltip
          :formatter="remarkHandler"
        />
        <el-table-column
          prop="status"
          label="状态"
          :formatter="statusHandler"
          align="center"
          min-width="20"
        />
        <el-table-column
          prop="created_at"
          label="注册时间"
          align="center"
          min-width="40"
        />

        <el-table-column min-width="30">
          <!-- eslint-disable-next-line vue/no-unused-vars -->
          <template slot="header" slot-scope="scope">
            <el-input
              v-model="fuzzySearchKeyword"
              placeholder="输入关键字搜索"
            />
          </template>

          <!-- eslint-disable-next-line vue/no-unused-vars -->
          <template slot-scope="scope">
            <el-dropdown split-button type="primary" align="center" trigger="click" @command="clickRowDropDown">
              <span class="el-dropdown-link">
                更多
              </span>
              <el-dropdown-menu slot="dropdown" trigger="click">
                <el-dropdown-item command="changPwd">修改密码</el-dropdown-item>
                <el-dropdown-item command="LockUser">锁定</el-dropdown-item>
                <el-dropdown-item command="UnlockUser">解锁</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 修改密码 -->
    <el-dialog
      :visible.sync="changePwdVisible"
      width="30%"
      @close="changePwdVisible = false"
    >
      <div slot="title" class="header-title">
        <div style="padding:15px 20px;">修改密码</div>
      </div>

      <el-form ref="updateUserData" :model="updateUserData" label-width="auto" style="margin-left: 100px" :rules="inputRules">

        <el-form-item
          class="opt"
          prop="password"
        >
          <el-input
            v-model="updateUserData.password"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            :type="flag?'text':'password'"
          >
            <i
              slot="suffix"
              :class="[flag?'el-icon-minus':'el-icon-view']"
              style="margin-top:8px;font-size:18px;"
              autocomplete="auto"
              @click="flag=!flag"
            />
          </el-input>
        </el-form-item>

        <el-form-item
          class="opt"
          prop="password"
        >
          <el-input
            v-model="confirmPwd"
            prefix-icon="el-icon-lock"
            placeholder="输入确认密码"
            :type="flag?'text':'password'"
          >
            <i
              slot="suffix"
              :class="[flag?'el-icon-minus':'el-icon-view']"
              style="margin-top:8px;font-size:18px;"
              autocomplete="auto"
              @click="flag=!flag"
            />
          </el-input>
        </el-form-item>

        <el-form-item
          class="opt"
        >
          <span style="color: red;"> 请输入8位至少3种组合的密码。可包含大小写字母、数字、特殊字符</span>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePwdVisible = false">取消</el-button>
        <el-button type="primary" @click="changePwdReq">提交</el-button>
      </span>
    </el-dialog>

    <!-- 锁定用户 -->
    <el-dialog
      :visible.sync="locakUserVisible"
      width="30%"
      @close="locakUserVisible=false"
    >
      <div slot="title" class="header-title">
        <div style="padding:15px 20px;">锁定用户</div>
      </div>
      <span>是否锁定用户？</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="locakUserVisible = false">取消</el-button>
        <el-button type="primary" @click="lockOrUnlockUser">提交</el-button>
      </span>
    </el-dialog>

    <!-- 解锁用户 -->
    <el-dialog
      :visible.sync="unlockUserVisible"
      width="30%"
      @close="unlockUserVisible=false"
    >
      <div slot="title" class="header-title">
        <div style="padding:15px 20px;">解锁用户</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="unlockUserVisible = false">取消</el-button>
        <el-button type="primary" @click="lockOrUnlockUser">提交</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户 -->
    <el-dialog
      :visible.sync="editUserVisible"
      width="35%"
      @close="editUserVisible = false"
    >
      <div slot="title" class="header-title">
        <div style="padding:15px 20px;">编辑用户</div>
      </div>
      <el-form
        ref="updateUserData"
        :model="updateUserData"
        label-width="auto"
        style="margin-left: 100px"
        :rules="inputRules"
      >

        <el-form-item label="手机：">
          <el-input
            v-model="updateUserData.phone"
            placeholder="请输入11位手机号"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="当前角色：">
          <div v-if="displayUserData.roles.length > 0">
            <el-tag
              v-for="(item, key) in displayUserData.roles"
              :key="key"
              style="margin: 3px;"
              size="medium"
            >{{ item.RoleName }}
            </el-tag>
          </div>
          <span v-else>暂无角色</span>
        </el-form-item>

        <el-form-item label="选择角色：" prop="roles">
          <div class="roles-list-box">

            <div class="role-list-eltable">
              <el-table
                ref="multipleRoleTable"
                align="center"
                :row-key="getRoleListRowKey"
                :data="rolesListData"
                tooltip-effect="dark"
                style="width: 100%"
                @select="rolesSelectChanged"
              >
                <el-table-column
                  type="selection"
                  :reserve-selection="true"
                  width="30"
                />
                <el-table-column
                  prop="RoleName"
                  label="角色名称"
                  width="auto"
                  show-overflow-tooltip
                />
              </el-table>
            </div>

            <div class="role-list-page">
              <el-pagination
                small
                layout="total, prev, pager, next, jumper"
                :total="roleListCount"
                :page-size="rolesListQuery.length"
                :pager-count="pagerCount"
                @current-change="rolesPageChanged"
              />
            </div>

          </div>

        </el-form-item>

        <el-form-item label="备注：">
          <el-input
            v-model="updateUserData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="20"
          />
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserReq">提交</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import { getRoles } from '@/api/lives'
import { getUsers, updateUsers } from '@/api/user'
import Clipboard from 'clipboard'
import { mapGetters } from 'vuex'
export default {
  name: 'SubjectSetting',
  directives: {
    'el-select-loadmore': {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          /**
				  * scrollHeight 获取元素内容高度(只读)
				  * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直	方向的滚动条, 那它的scrollTop的值默认为0.
				  * clientHeight 读取元素的可见高度(只读)
				  * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
				  * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
          */
          const condition = this.scrollHeight - (this.scrollTop + 1) <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    return {
      // 分页前选择的角色信息
      // 用来确定哪些最初的项被取消了
      preCheckboxSelectedRoles: [],
      // 当选择有变化时，用来保存当前的变化
      currentCheckboxSelectedRoles: [],
      flag: false,
      inputRules: {
        roles: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'bulr' }
        ]
      },
      // 列表下拉更新操作的类型
      actionType: '',
      // 用户可设置的最大数量
      userRolesLimit: 10,
      // 模糊查询关键字
      fuzzySearchKeyword: '',
      // 是否可以编辑
      edituserDisabled: true,
      editUserVisible: false,
      changePwdVisible: false,
      locakUserVisible: false,
      unlockUserVisible: false,
      // 是否获取所的角色标志
      isGetAllRoles: false,
      rolesListData: [],
      // 文件上传地址
      fileUploadAddr: '',
      fileUploadHeaders: {
        Authorization: ''
      },
      userListCount: 0,
      userListData: [],
      roleListCount: 0,
      tableRadio: undefined,
      pagerCount: 5,
      // 获取用户列表请求
      userListQuery: {
        start: 1,
        length: 14,
        keyword: '',
        order: 'desc'
      },
      // 获取角色列表请求
      rolesListQuery: {
        start: 1,
        length: 14,
        keyword: '',
        order: 'desc'
      },
      // 更新用户请求
      updateUserData: {
        password: '',
        lock: false,
        roles: [],
        phone: '',
        remark: ''
      },
      confirmPwd: '',
      // 展示用户数据(不可修改的数据)
      displayUserData: {
        UserName: '',
        roles: []
      }
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  watch: {
    userListQuery: {
      handler(n, o) {
        this.refreshUsers()
      },
      deep: true
    },
    rolesListQuery: {
      handler(n, o) {
        this.refrshRoles()
      },
      deep: true
    },
    'token'(n, o) {
      this.fileUploadHeaders.Authorization = n
    },
    'fuzzySearchKeyword'(n, o) {
      this.userListQuery.keyword = n
    }
  },
  mounted() {
    // 用户列表
    this.refreshUsers()
    // 上传文件的地址
    this.fileUploadAddr = process.env.VUE_APP_BASE_API + '/api/v1/files'
    // 设置访问头
    this.fileUploadHeaders.Authorization = this.token
  },
  methods: {
    // 设置默认选中的项
    toggleRolesSelection() {
      if (this.displayUserData.roles.length > 0) {
        this.$nextTick(() => {
          this.displayUserData.roles.forEach(checkedRow => {
            var cID = checkedRow.id
            this.rolesListData.forEach(listRow => {
              var lID = listRow.id
              if (lID === cID) {
                this.$refs.multipleRoleTable.toggleRowSelection(listRow, true)
              }
            })
          })
        })
      }
    },
    // 编辑用户选择角色时的变化
    rolesSelectChanged(selection, row) {
      var tempDisplayRoles = []
      // 该行是否已取消
      var d = [row].filter(function(v) { return selection.indexOf(v) === -1 })
      if (d.length > 0) {
        var dID = d[0].id
        for (var i = 0; i < this.displayUserData.roles.length; i++) {
          var ID = this.displayUserData.roles[i].id
          if (dID !== ID) {
            tempDisplayRoles.push(this.displayUserData.roles[i])
          }
        }
        this.displayUserData.roles = tempDisplayRoles
      } else {
        tempDisplayRoles = selection
      }
      var f = tempDisplayRoles.concat(this.displayUserData.roles.filter(function(v) { return !(tempDisplayRoles.indexOf(v) > -1) }))
      this.displayUserData.roles = f
      if (this.displayUserData.roles.length > this.userRolesLimit) {
        this.$message({
          message: `用户角色最大不能超过${this.userRolesLimit}个`,
          type: 'warning'
        })
        return
      }
    },
    // 角色分页时
    rolesPageChanged(ev) {
      this.preCheckboxSelectedRoles = ''
      this.rolesListQuery.start = ev
    },
    elTableHeaderStyle() {
      return {
        background: '#F0F1F2',
        font_size: '18px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#6D7A8E'
      }
    },
    elTableCellStyle() {
      return {
        font_size: '20px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#8B9DBA'
      }
    },
    // 选择行变化时
    clickRowChange(ev) {
      this.tableRadio = ev
      // 可删除
      this.deleteLiveDisabled = false
      // 可编辑
      this.edituserDisabled = false
    },
    // 用户列表翻页
    pageChanged(ev) {
      this.userListQuery.start = ev
    },
    // 刷新角色
    refrshRoles() {
      this.getRoleListReq()
    },
    // 刷新用户列表
    refreshUsers() {
      getUsers(this.userListQuery).then((res) => {
        if (res.code === 200) {
          this.userListData = res.data
          this.userListCount = res.count
        }
      })
    },
    handleCopy(cls) {
      var clipboard = new Clipboard(cls)
      clipboard.on('success', e => {
        this.$message({
          message: '已复制',
          type: 'success'
        })
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        console.log('该浏览器不支持自动复制')
        // 释放内存
        clipboard.destroy()
      })
    },
    // 更新用户
    updateUserReq(data, userID) {
      updateUsers(data, userID).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
        this.editLiveOuterVisible = false
      }).catch(() => {
        this.$message.error('修改失败')
      })
    },
    // 下拉选中时
    clickRowDropDown(command) {
      this.actionType = command
      // 修改密码
      if (command === 'changPwd') {
        this.changePwdVisible = true
      } else if (command === 'LockUser') {
        this.locakUserVisible = true
      } else if (command === 'UnlockUser') {
        this.unlockUserVisible = true
      }
    },
    // 点击编辑用户时的处理
    editUserHandler() {
      if (this.tableRadio.UserRoles) {
        this.displayUserData.roles = []
        this.updateUserData.phone = this.tableRadio.phone
        this.updateUserData.remark = this.tableRadio.remark
        if (this.tableRadio.password) {
          this.updateUserData.password = this.tableRadio.password
          this.confirmPwd = this.tableRadio.password
        }
        for (var i = 0; i < this.tableRadio.UserRoles.length; i++) {
          var data = {
            id: this.tableRadio.UserRoles[i].RoleId,
            RoleName: this.tableRadio.UserRoles[i].RoleName
          }
          this.displayUserData.roles.push(data)
        }
      }
      // this.displayUserData.roles = this.tableRadio.UserRoles || []
      this.updateUserData.roles = []
      this.getRoleListReq()
      this.editUserVisible = true
    },
    getRoleListReq() {
      getRoles(this.rolesListQuery).then((res) => {
        if (res.data.length > 0) {
          this.rolesListData = res.data
          this.roleListCount = res.count
          this.toggleRolesSelection()
        }
      })
    },
    getRoleListRowKey(row) {
      return row.id
    },
    // ========== 列表字段方法集 ===========
    // 角色名
    roleNameHandler(row) {
      var roles = []
      for (var i = 0; i < row.UserRoles.length; i++) {
        roles.push(row.UserRoles[i].RoleName)
      }
      return roles.toString()
    },
    // 用户状态
    statusHandler(row) {
      if (row.status === 1) {
        return '启用'
      } else {
        return '禁用'
      }
    },
    // 用户名
    userNameHandler(row) {
      if (!row.UserName || row.UserName.length === 0) {
        return '未设置'
      }
      return row.UserName
    },
    // 联系电话
    phoneHandler(row) {
      if (!row.phone || row.phone.length === 0) {
        return '未设置'
      }
      return row.phone
    },
    // 联系电话
    remarkHandler(row) {
      if (!row.remark || row.remark.length === 0) {
        return '未设置'
      }
      return row.remark
    },
    // ============更新用户方法集=================
    // 修改用户密码
    changePwdReq() {
      if (this.confirmPwd !== this.updateUserData.password) {
        this.$message.error('两次密码不一至')
        return
      }
      // base64解码
      var b64Pwd = btoa(this.confirmPwd)
      var updateData = {
        password: b64Pwd
      }
      this.updateUserReq(updateData, this.tableRadio.id)
    },
    // 锁定/解锁
    lockOrUnlockUser() {
      var action = false
      if (this.actionType === 'LockUser') {
        action = true
      }
      var updateData = {
        lock: action
      }
      this.updateUserReq(updateData, this.tableRadio.id)
    },
    // 编辑用户
    editUserReq() {
      var roleIDs = []
      for (var i = 0; i < this.displayUserData.roles.length; i++) {
        roleIDs.push(this.displayUserData.roles[i].id)
      }
      var updateData = {
        roles: roleIDs,
        phone: this.updateUserData.phone,
        remark: this.updateUserData.remark
      }
      this.updateUserReq(updateData, this.tableRadio.id)
      this.editUserVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container-box {
  height: 1010px;

}
.box-tag {
  width: 4px;
  height: 28px;
  background: #2E9BEA;
  border-radius: 2px;
  position: relative;
  top: 25px;
}
.warp-line-top {
  width: 1627px;
  height: 4px;
  background: #EDF5FB;
  top: 85px;
  position: absolute;
}

.table-list-box {
  position: absolute;
  top: 176px;
  left: 55px;
  width: 1518px;
  height: 654px;
}
.btn-box {
  position: absolute;
  display: flex;
  align-items: center;
  width: 100%;
  top: 114px;
  left: 54px;
  .input-with-select {
    margin: 20px;
    left: 600px;
  }
  .page-box {
    right: 125px;
    position: absolute;
  }
}

.user-manager-title {
    width: 207px;
    height: 24px;
    font-size: 24px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #4A5462;
    position: absolute;
    top: 27px;
    left: 44px;
  }
.el-form-item {
  width: 70%;
}
.roles-list-box {
    width: 100%;
    height: 300px;
    border: 1px black solid;
    .roles-list-title-box {
      width: auto;
      height: 30px;
      background-color: red;
      }
    .role-list-eltable {
      overflow: auto;
      width: auto;
      height: 270px;
      ::v-deep {
        .el-table__header-wrapper  .el-checkbox{
          display:none
        }
      }
    }
    .role-list-page {
      width: auto;
      height: 30px;
      background-color: #FFFFFF;
      border-bottom: 1px black solid;
      display: flex;
      flex-direction: row-reverse;
    }
  }
</style>
